<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--<%@ page isELIgnored="false" %>--%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>${live.title} - 直播</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入hls.js用于播放直播流 -->
    <script src="https://cdn.jsdelivr.net/npm/hls.js@1.4.14/dist/hls.min.js"></script>
    <style>
        /*#recording-container {*/
        /*    position: absolute;*/
        /*    top: 10px;*/
        /*    right: 10px;*/
        /*    z-index: 100;*/
        /*    background-color: rgba(0, 0, 0, 0.7);*/
        /*    border-radius: 10px;*/
        /*    padding: 8px;*/
        /*    display: flex;*/
        /*    flex-direction: column;*/
        /*    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);*/
        /*    max-width: 200px; !* 限制最大宽度 *!*/
        /*}*/

        .video-container {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #000;
            border-radius: 10px;
            overflow: hidden;
        }
        #recording-video {
            width: 100%;
            max-width: 180px;
            border-radius: 5px;
            margin-bottom: 8px;
        }
        .recording-controls {
            display: flex;
            gap: 4px;
            width: 100%;
        }
        .recording-controls button {
            flex: 1;
            padding: 4px;
            font-size: 10px;
        }
        #recording-timer {
            margin-top: 4px;
            font-size: 12px;
            color: #ff4d4f;
        }
        #container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            align-items: center;
        }
        .controls {
            padding: 0 10px;
        }
        /* 响应式设计 - 小屏幕上调整录制框位置 */
        @media (max-width: 768px) {
            #recording-container {
                top: 8px;
                right: 800px;
                padding: 6px;
            }
            #recording-video {
                max-width: 140px;
            }
            .recording-controls button {
                padding: 3px;
                font-size: 8px;
            }
            #recording-timer {
                font-size: 10px;
            }

        }
    </style>
</head>
<body class="bg-gray-900 text-white">
<div class="container mx-auto px-4 py-8">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold">${live.title}</h1>
        <div class="flex space-x-4">
            <button id="shareBtn" class="flex items-center bg-gray-800 hover:bg-gray-700 px-4 py-2 rounded-lg transition-smooth">
                <i class="fa fa-share-alt mr-2"></i> 分享
            </button>
            <button id="followBtn" class="flex items-center bg-primary hover:bg-primary/90 px-4 py-2 rounded-lg transition-smooth">
                <i class="fa fa-heart-o mr-2"></i> 关注
            </button>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 左侧主区域 - 占据2/3宽度 -->
        <div class="lg:col-span-2 space-y-6">
            <!-- 视频区域 -->
            <div class="video-container">
                <!-- 摄像头录制模块 -->
                <div id="recording-container" class="w-full h-full flex flex-col items-center justify-center">
                    <video id="gum" class="w-full h-full object-contain" autoplay muted></video>
                    <div class="recording-controls mt-4 w-full flex gap-2 p-4">
                        <button id="record" class="flex-1 py-2 bg-primary hover:bg-primary/90 rounded-lg text-white transition-smooth">
                            <i class="fa fa-circle mr-2"></i> 开始直播
                        </button>
                        <button id="play" class="flex-1 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg text-white transition-smooth" disabled>
                            <i class="fa fa-play mr-2"></i> 播放
                        </button>
                        <button id="download" class="flex-1 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg text-white transition-smooth" disabled>
                            <i class="fa fa-download mr-2"></i> 下载
                        </button>
                    </div>
                    <div id="tEl" class="mt-2 text-white text-center"></div>
                </div>
            </div>

            <!-- 商品信息区域 - 移动到视频下方 -->
            <div class="bg-gray-800 rounded-lg p-6">
                <h2 class="text-xl font-semibold mb-2">外语直播</h2>
                <p class="text-gray-400">提高外语的交流能力</p>
                <div class="mt-4 flex items-center">
                    <img src="https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif" alt="主播头像" class="w-10 h-10 rounded-full object-cover">
                    <div class="ml-3">
                        <p class="font-medium">教师</p>
                        <p class="text-sm text-gray-400">开播时间: ${live.startTime}</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧聊天区 - 占据1/3宽度 -->
        <div class="bg-gray-800 rounded-lg overflow-hidden flex flex-col h-[600px]">
            <div class="p-4 border-b border-gray-700">
                <h3 class="font-semibold">聊天区</h3>
            </div>
            <div id="chatMessages" class="flex-1 p-4 overflow-y-auto space-y-4">
                <!-- 聊天消息将动态加载到这里 -->
            </div>
            <div class="p-4 border-t border-gray-700">
                <div class="flex">
                    <input type="text" id="chatInput" placeholder="发送消息..." class="flex-1 bg-gray-700 border border-gray-600 rounded-l-lg px-4 py-2 focus:outline-none focus:ring-1 focus:ring-primary">
                    <button id="sendChatBtn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-r-lg transition-smooth">
                        发送
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    // 摄像头录制功能类（与之前版本相同，主要修改了CSS布局）
    class RecordingVideo {
        // 播放时长
        duration = 0;
        // 录制流媒体
        mediaRecorder;
        // 录制的数据
        recordedBlobs = [];
        // 倒计时interval
        intervalId;
        // 摄像头流媒体
        stream;
        // 录制时长
        maxD = 600; // 默认为60秒
        // 倒计时初始值
        count = 600;
        // 页面dom
        gumVideo = document.querySelector('#gum');
        recordButton = document.querySelector('#record');
        playButton = document.querySelector('#play');
        downloadButton = document.querySelector('#download');
        tEL = document.getElementById('tEl');

        constructor(autoStart = false) {
            const constraints = {
                audio: true,
                video: {
                    facingMode: "user",
                    width: 1280,  // 调整为更大的分辨率
                    height: 720,
                    frameRate: 30
                }
            };

            const isSecureOrigin = location.protocol === 'https:' || location.hostname === 'localhost';
            if (!isSecureOrigin) {
                alert('getUserMedia() 必须在https或localhost下使用');
                location.protocol = 'HTTPS';
                return;
            }

            this.recordButton.onclick = () => this.toggleRecording();
            this.playButton.onclick = () => this.play();
            this.downloadButton.onclick = () => this.download();

            this.gumVideo.width = constraints.video.width;
            this.gumVideo.height = constraints.video.height;

            // 获取摄像头流媒体
            this.getUserMedia(
                constraints,
                (stream) => {
                    // 摄像头流媒体成功回调
                    this.recordButton.disabled = false;
                    this.stream = stream;
                    this.gumVideo.srcObject = stream;

                    // 如果需要自动开始录制
                    if (autoStart) {
                        setTimeout(() => this.startRecording(), 1000);
                    }
                },
                (error) => {
                    // 摄像头流媒体失败回调
                    if (error.message === 'Permission denied') {
                        alert('您已经禁止使用摄像头，请到设置-然后选择获取权限');
                    }
                    console.log('navigator.getUserMedia error: ', error);
                }
            );
        }

        // 获取摄像头流媒体
        getUserMedia(constraints, success, error) {
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                // 最新的标准API
                navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
            } else if (navigator.webkitGetUserMedia) {
                // webkit核心浏览器
                navigator.webkitGetUserMedia(constraints, success, error);
            } else if (navigator.mozGetUserMedia) {
                // firfox浏览器
                navigator.mozGetUserMedia(constraints, success, error);
            } else if (navigator.getUserMedia) {
                // 旧版API
                navigator.getUserMedia(constraints, success, error);
            } else {
                error(new Error('不支持getUserMedia API'));
            }
        }

        // 开始/停止录制
        toggleRecording() {
            if (this.recordButton.textContent === '开始录制') {
                this.startRecording();
            } else {
                this.stopRecording();
            }
        }

        // 开始录制
        startRecording() {
            this.tEL.innerHTML = '';
            this.count = this.maxD;
            this.recordedBlobs = [];

            const isSafari = /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent);
            const options = {
                audioBitsPerSecond: 128000,
                videoBitsPerSecond: 2500000,
                mimeType: isSafari ? 'video/mp4' : 'video/webm'
            };

            try {
                this.mediaRecorder = new MediaRecorder(this.stream, options);
            } catch (e) {
                alert('MediaRecorder创建失败: ' + e + '. mimeType: ' + options.mimeType);
                return;
            }

            this.recordButton.textContent = '结束录制';
            this.downloadButton.disabled = true;
            this.playButton.disabled = true;

            // 更新倒计时显示
            this.updateCountdown();
            this.intervalId = setInterval(() => this.updateCountdown(), 1000);

            // 录制数据回调
            this.mediaRecorder.ondataavailable = event => {
                if (event.data && event.data.size > 0) {
                    this.recordedBlobs.push(event.data);
                }
            };

            // 录制结束回调
            this.mediaRecorder.onstop = () => {
                clearInterval(this.intervalId);
                this.tEL.innerHTML = '录制完成';
                this.duration = this.maxD - this.count;
                this.recordButton.textContent = '开始录制';
                this.playButton.disabled = false;
                this.downloadButton.disabled = false;
            };

            // 开始录制，每10ms收集一次数据
            this.mediaRecorder.start(10);
        }

        // 更新倒计时
        updateCountdown() {
            this.tEL.innerHTML = '剩余时间：' + this.count + '秒';
            if (this.count <= 0) {
                this.stopRecording();
            } else {
                this.count--;
            }
        }

        // 停止录制
        stopRecording() {
            if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
                this.mediaRecorder.stop();
            }
        }

        // 下载视频
        download() {
            const blob = new Blob(this.recordedBlobs, { type: 'video/mp4' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = '直播录制_' + Date.now() + '.mp4';
            document.body.appendChild(a);
            a.click();
            setTimeout(() => {
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            }, 100);
        }

        // 播放视频
        play() {
            const blob = new Blob(this.recordedBlobs, { type: 'video/mp4' });
            const size = parseInt(blob.size / 1024);
            const strSize = size < 1024 ? size + 'KB' : (size/1024).toFixed(2) + 'MB';

            alert('播放时长：' + this.duration + '秒, 大小：' + strSize);

            const playVideo = document.createElement('video');
            playVideo.controls = true;
            playVideo.src = URL.createObjectURL(blob);
            playVideo.className = 'fixed inset-0 z-50 w-full h-full object-contain';
            document.body.appendChild(playVideo);

            playVideo.onended = () => {
                document.body.removeChild(playVideo);
            };
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        // 初始化直播播放器（与之前版本相同）
        const video = document.getElementById('livePlayer');
        const loadingIndicator = document.getElementById('loadingIndicator');

        if (Hls.isSupported()) {
            const hls = new Hls();
            const streamUrl = '${pageContext.request.contextPath}/live/stream/${live.streamKey}.m3u8';

            hls.loadSource(streamUrl);
            hls.attachMedia(video);

            hls.on(Hls.Events.MANIFEST_PARSED, function() {
                loadingIndicator.classList.add('hidden');
                video.play();
            });

            hls.on(Hls.Events.ERROR, function(event, data) {
                console.error('HLS error:', data);
                if (data.fatal) {
                    switch(data.type) {
                        case Hls.ErrorTypes.NETWORK_ERROR:
                            console.log('尝试重新连接...');
                            hls.startLoad();
                            break;
                        case Hls.ErrorTypes.MEDIA_ERROR:
                            console.log('尝试修复媒体错误...');
                            hls.recoverMediaError();
                            break;
                        default:
                            console.log('无法恢复错误，直播已中断');
                            hls.destroy();
                            loadingIndicator.classList.add('hidden');
                            alert('直播已中断');
                            break;
                    }
                }
            });
        } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
            video.src = '${pageContext.request.contextPath}/live/stream/${live.streamKey}.m3u8';
            video.addEventListener('loadedmetadata', function() {
                loadingIndicator.classList.add('hidden');
                video.play();
            });
        }

        // 聊天功能实现（与之前版本相同）
        const chatInput = document.getElementById('chatInput');
        const sendChatBtn = document.getElementById('sendChatBtn');
        const chatMessages = document.getElementById('chatMessages');

        // 模拟发送聊天消息1
        <%--function addChatMessage(username, message, isSelf = false) {--%>
        <%--    const messageElement = document.createElement('div');--%>
        <%--    messageElement.className = isSelf ? 'flex justify-end' : 'flex';--%>

        <%--    messageElement.innerHTML = `--%>
        <%--    <div class="${isSelf ? 'bg-primary/20 text-white' : 'bg-gray-700 text-white'} p-3 rounded-lg max-w-[80%]">--%>
        <%--        <div class="font-medium text-sm">\${username}</div>--%>
        <%--        <div class="text-sm mt-1">\${message}</div>--%>
        <%--    </div>--%>
        <%--`;--%>

        <%--    chatMessages.appendChild(messageElement);--%>
        <%--    chatMessages.scrollTop = chatMessages.scrollHeight;--%>
        <%--}--%>
        //模拟发送聊天消息2 和上面的方法1都可行
        function addChatMessage(username, message, isSelf = false) {
            const chatMessages = document.getElementById('chatMessages'); // 确保正确获取
            if (!chatMessages) {
                console.error('chatMessages element not found');
                return;
            }
            const messageElement = document.createElement('div');
            messageElement.className = isSelf ? 'flex justify-end' : 'flex';
            const contentElement = document.createElement('div');
            contentElement.className = isSelf ? 'bg-primary/20 text-white' : 'bg-gray-700 text-white';
            contentElement.classList.add('p-3', 'rounded-lg', 'max-w-[80%]');
            const usernameElement = document.createElement('div');
            usernameElement.className = 'font-medium text-sm';
            usernameElement.textContent = username;
            const messageContentElement = document.createElement('div');
            messageContentElement.className = 'text-sm mt-1';
            messageContentElement.textContent = message; // 直接显示文本

            contentElement.appendChild(usernameElement);
            contentElement.appendChild(messageContentElement);
            messageElement.appendChild(contentElement);
            chatMessages.appendChild(messageElement);

            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        function sendMessage() {
            const message = chatInput.value.trim();
            if (message) {
                addChatMessage('我', message, true);

                fetch('${pageContext.request.contextPath}/live/${live.id}/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        message: message
                    })
                })
                    .then(response => response.json())
                    .then(data => {
                        if (!data.success) {
                            console.error('发送消息失败:', data.message);
                        }
                    })
                    .catch(error => {
                        console.error('发送消息网络错误:', error);
                    });

                chatInput.value = '';
            }
        }

        sendChatBtn.addEventListener('click', sendMessage);
        chatInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // 模拟接收消息（与之前版本相同）
        setInterval(function() {
            const randomUsers = ['柴俊杰', '曹桂治', '强虎', '小尚', '小张'];
            const randomMessages = [
                '老师讲得太精彩了!',
                '支持老师！讲得真细致!',
                '老师讲课逻辑清晰，一听就懂!',
                '这个知识点讲得太透彻了!',
                '老师声音好听，讲课还这么专业!',
                '干货满满，受益匪浅!',
                '老师讲得真耐心，太适合学习了!',
                '思路清晰，重点突出，太棒了!',
                '老师讲得真生动，一点都不枯燥!',
                '这堂课太值了，感谢老师！',
                '老师讲得太好了，完全被吸引住了!',
                '例子举得太贴切了，一听就明白!',
                '老师讲得真细致，每个点都讲透了!',
                '节奏把握得太好了，听着很舒服!',
                '老师讲得太专业了，必须点赞!',
                '这堂课真的学到很多，谢谢老师!',
                '老师讲得太有趣了，一点不犯困!',
                '思路清晰，表达流畅，太强了!',
                '老师讲得太实用了，马上就能用上!',
                '讲得真细致，每个细节都照顾到了!',
                '老师讲得太有激情了，听着都兴奋!',
                '这堂课真的超值，收获满满!',
                '老师讲得太通俗易懂了，适合小白!',
                '逻辑严谨，讲解透彻，太厉害了!',
                '老师讲得太生动了，一点都不枯燥!',
                '互动感很强，听课体验超棒!',
                '老师讲得太有深度了，专业度满分!',
                '课堂氛围很好，老师讲得真投入!',
                '讲得太好了，完全被吸引住了!',
                '老师讲得太精彩了，期待下一节!'
            ];


            if (Math.random() > 0.7) {
                const randomUser = randomUsers[Math.floor(Math.random() * randomUsers.length)];
                const randomMessage = randomMessages[Math.floor(Math.random() * randomMessages.length)];
                addChatMessage(randomUser, randomMessage);
            }
        }, 5000);

        // 初始化摄像头录制功能，并设置自动开始录制
        try {
            const recordingInstance = new RecordingVideo(true);
        } catch (error) {
            console.error('摄像头录制功能初始化失败:', error);
            alert('摄像头初始化失败，请检查浏览器权限设置');
        }
    });
</script>
</body>
</html>